<template>
  <div class="wrapper">
    <el-aside class="sider">
      <div class="topslid">
        <img class="rolImg" src="@/assets/img/role.png" alt />
        <div class="rolTit">组织架构</div>
        <img  v-if="isAuthBtnS('extra1')" class="addImg" src="@/assets/img/add.png" alt @click="addpart" />
      </div>
      <el-tree
        :data="roleszTreeNodes"
        node-key="id"
        ref="tree"
        :props="defaultProps"
        @node-click="searchRole"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span class="rowIcon" v-if="data.GROUP_NAME=='0'">
            <el-button  v-if="isAuthBtnS('extra2')" type="text" size="mini" @click="() => append(data)">新增</el-button>
            <el-button  v-if="isAuthBtnS('edit')" type="text" size="mini" @click="() => edit(data)">编辑</el-button>
            <el-button  v-if="isAuthBtnS('del')" type="text" size="mini" @click="() => delRol(data)">删除</el-button>
          </span>
          <span class="rowIcon" v-if="data.GROUP_NAME=='1'">
            <el-button  v-if="isAuthBtnS('extra3')" type="text" size="mini" @click="() => edit(data)">编辑</el-button>
            <el-button  v-if="isAuthBtnS('extra4')" type="text" size="mini" @click="() => delRol(data)">删除</el-button>
          </span>
        </span>
      </el-tree>
      <!-- <div
        v-for="(item,index) in roleList"
        :key="index"
        class="rowItem"
        :class="[item.id==roleId?'active':'']"
        @click="searchRole(item)"
      >
        <div class="rowleft">{{item.name}}</div>
        <div class="rowright" @click="delRol(item)">
          <img class="rowIcon" src="@/assets/img/del.png" alt />
        </div>
      </div>-->
    </el-aside>
    <el-main>
      <el-tree
        :data="dataList"
        show-checkbox
        node-key="keyId"
        ref="tree"
        :check-strictly="true"
        :default-expanded-keys="expendKey"
        :props="defaultProps"
        @check="clickDeal"
      ></el-tree>
      <div style="padding:20px;" v-if="isAuthBtnS('add')">
        <el-button type="primary" size="small" @click="saveRole">保存</el-button>
      </div>
    </el-main>
    <el-dialog :visible.sync="addRoleVisible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm">
        <el-form-item :label="GROUP_NAME=='1'?'角色名称':'部门名称'" prop="roleName">
          <el-input v-model="dataForm.roleName" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from "./posi-update";
import { treeDataTranslate } from "@/utils";

export default {
  components: { AddOrUpdate },
  data() {
    return {
      qxlist:{},
      GROUP_NAME: "", //= 0 是部门 1 角色
      PARENT_ID: "",
      dataForm: {
        roleName: ""
      },
      roleszTreeNodes: [],
      addRoleVisible: false,
      dataList: [],
      roleId: "",
      roleList: [],
      expendKey: [],
      checkdList: [],
      multipleSelection: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      dataRule: {
        roleName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        partName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ]
      },
      menuListTreeProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
     // 获取数据列表
    isAuthBtnS(data) {
      return this.qxlist && this.qxlist[data] && this.qxlist[data] == "1"
        ? true
        : false;
    },
    addRole() {
      this.GROUP_NAME = 1;
      this.addRoleVisible = true;
    },
    addpart() {
      this.GROUP_NAME = 0;
      this.PARENT_ID = 0;
      this.dataForm.id = "";
      this.addRoleVisible = true;
    },
    append(data) {
      this.GROUP_NAME = 1;
      this.dataForm.id = "";
      this.PARENT_ID = data.id;
      this.addRoleVisible = true;
    },
    edit(data) {
      console.log(data);
      this.GROUP_NAME = data.GROUP_NAME;
      this.dataForm = Object.assign({}, this.dataForm, {
        roleName: data.name,
        id: data.id
      });
      this.PARENT_ID = data.PARENT_ID;
      this.addRoleVisible = true;
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/role/extend/${this.dataForm.id ? "edit" : "add"}.do`
            ),
            method: "post",
            data: this.$http.adornData({
              ROLE_NAME: this.dataForm.roleName,
              ROLE_ID: this.dataForm.id,
              data: JSON.stringify({
                id: this.dataForm.id,
                ROLE_ID: this.dataForm.id,
                PARENT_ID: this.PARENT_ID,
                GROUP_NAME: this.GROUP_NAME,
                ROLE_NAME: this.dataForm.roleName
              })
            })
          }).then(({ data }) => {
            this.getDataList();
            if (data.result == "1") {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.addRoleVisible = false;
                }
              });
            } else {
              this.$message.error(data.message);
            }
          });
        }
      });
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrl("/role/extend/role"),
        method: "post",
        data: this.$http.adornData()
      }).then(({ data }) => {

 this.qxlist = Object.assign({}, this.qxList, data.QX);

        this.roleszTreeNodes = treeDataTranslate(
          data.roleszTreeNodes,
          "id",
          "pId"
        );
      });
    },
    searchRole(item) {
      this.roleId = item.ROLE_ID;
      this.$http({
        url: this.$http.adornUrl("/role/extend/authority/framework.do"),
        method: "post",
        data: this.$http.adornData({
          ROLE_ID: item.ROLE_ID
        })
      }).then(({ data }) => {
        this.dataList = treeDataTranslate(data.zTreeNodes, "id", "pId");
        let checkdList = data.zTreeNodes.filter(item => item.checked);
        this.expendKey = checkdList.map(item => item.pId);
        this.checkdList = checkdList.map(item => item.keyId);
        this.$refs.tree.setCheckedKeys(this.checkdList);
      });
    },
    saveRole() {
      let checkdList = this.$refs.tree
        .getCheckedNodes()
        .map(item => item.id + "@" + item.pId);

      let defaultListr = this.$refs.tree
        .getHalfCheckedNodes()
        .map(item => item.id + "@" + item.pId);
      checkdList = checkdList.concat(defaultListr);

      this.$http({
        url: this.$http.adornUrl("/role/extend/auth/save.do"),
        method: "post",
        data: this.$http.adornData({
          ROLE_ID: this.roleId,
          menuIds: checkdList.join(",")
        })
      }).then(({ data }) => {
        if (data && data.result == "1") {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {}
          });
        } else {
          this.$message.error(data.message);
        }
      });
    },
    delRol(item) {
      this.$confirm(`确定对[角色：${item.name}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/role/extend/checkdata.do"),
            method: "post",
            data: this.$http.adornData({
              ROLE_ID: item.ROLE_ID
            })
          }).then(({ data }) => {
            if (data && dataresult == "1") {
              this.delRolUser(item);
            } else {
              this.$message.error(data.message);
            }
          });
        })
        .catch(() => {});
    },
    delRolUser(item) {
      this.$http({
        url: this.$http.adornUrl("/role/extend/delete.do"),
        method: "post",
        data: this.$http.adornData({
          ROLE_ID: item.ROLE_ID
        })
      }).then(({ data }) => {
        console.log(res);
        if (data && data.result == "1") {
          this.getDataList();
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {}
          });
        } else {
          this.$message.error(data.message);
        }
      });
    },
    // 新增 / 修改
    clickDeal(currentObj, treeStatus) {
      // console.log(currentObj, treeStatus);
      let selected = treeStatus.checkedKeys.indexOf(currentObj.keyId); // -1未选中
      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectedParent(currentObj);
        // 统一处理子节点为相同的勾选状态
        this.unitechildrename(currentObj, true);
      } else {
        // 未选中 处理子节点全部未选中
        if (currentObj.children && currentObj.children.length !== 0) {
          this.unitechildrename(currentObj, false);
        }
      }
    },
    // 统一处理子节点为相同的勾选状态
    unitechildrename(treeList, isSelected) {
      console.log(treeList);
      this.$refs.tree.setChecked(treeList.keyId, isSelected);
      if (treeList.children) {
        for (let i = 0; i < treeList.children.length; i++) {
          this.unitechildrename(treeList.children[i], isSelected);
        }
      }
    },
    // 统一处理父节点为选中
    selectedParent(currentObj) {
      let currentNode = this.$refs.tree.getNode(currentObj);

      console.log(currentNode);
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true);
        this.selectedParent(currentNode.parent);
      }
    },
    handleNodeClick(data) {
      console.log(data);
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>

<style lang="scss">
.wrapper {
  display: flex;
  flex: 1;
  margin: -20px;
}
.topOpt {
  background-color: #f2f2f2;
  padding: 10px 20px;
}
.topslid {
  background-color: #1890ff;

  padding: 10px 0;

  color: #ffffff;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.rolImg {
  width: 20px;
  height: 20px;
  margin: 0 15px;
}
.rolTit {
  flex: 1;
  text-align: left;
  font-size: 16px;
  line-height: 1;
}
.addImg {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}
.sider {
  border-right: 1px solid #cccccc;
  height: 100%;
}
.topBar {
  padding: 10px;
  font-size: 18px;
  font-weight: bold;
}
.rowItem {
  display: flex;
  padding: 10px 0;
  cursor: pointer;
  &.active {
    background-color: #f2f2f2;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.rowItem:hover {
  background-color: #f2f2f2;
}
.custom-tree-node:hover .rowIcon {
  display: flex;
}
.rowleft {
  flex: 1;
  padding-left: 50px;
  font-size: 16px;
}
.rowIcon {
  display: none;
}
.rowright {
  width: 50px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>